﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
using InTheHand.Net; // e.g. BluetoothAddress, BluetoothEndPoint etc
using InTheHand.Net.Sockets; // e.g. BluetoothDeviceInfo, BluetoothClient, BluetoothListener
using InTheHand.Net.Bluetooth; // e.g. BluetoothService, BluetoothRadio

namespace RLGDashboard
{
    public partial class LoadScreen : Form
    {
        private BluetoothDeviceInfo[] devices;
        private BluetoothConnection bluetoothHandler;
        private EngineeringReplay replayHandler;

        string deviceName;

        public LoadScreen()
        {
            InitializeComponent();
            initilazeObjects();
        }

        private void initilazeObjects()
        {
            bluetoothHandler = new BluetoothConnection();
        }

        private void findDevices_Click(object sender, EventArgs e)
        {
            foundDevicesList.Items.Clear();
            foundDevicesList.Refresh();

            devices = bluetoothHandler.findDevices();
            foreach (BluetoothDeviceInfo i in devices)
            {
                foundDevicesList.Items.Add(i.DeviceName);

                findDevices.Enabled = false;
                SelectDevice.Enabled = true;
            }

            if (devices.Length == 0)
            {
                foundDevicesList.Items.Add("No Devices Found");
            }
        }

        private void SelectDevice_Click(object sender, EventArgs e)
        {
            deviceName = (string)foundDevicesList.SelectedItem;
            bluetoothHandler.selectDevice(deviceName);

            if(bluetoothHandler.isConnected())
            {
                RLGDashboard form = new RLGDashboard(bluetoothHandler, this);
                form.Show();

                this.Visible = false;
            }
        }

        private void runSimulation_Click(object sender, EventArgs e)
        {
            // Create an instance of the open file dialog box.
            OpenFileDialog openFileDialog1 = new OpenFileDialog();

            // Set filter options and filter index.
            openFileDialog1.Filter = "Text Files (.txt)|*.txt|All Files (*.*)|*.*";

            // Call the ShowDialog method to show the dialog box.
            DialogResult result = openFileDialog1.ShowDialog();

            if (result == DialogResult.OK)
            {
                EventWaitHandle waitHandle = new AutoResetEvent(false);
                string fileName = openFileDialog1.SafeFileName;
                replayHandler = new EngineeringReplay(fileName);
                RLGDashboard form = new RLGDashboard(replayHandler, this);

                form.Show();
                this.Visible = false;
            }
        }
    }
}
